/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.userCart.controller;

import static org.mockito.Matchers.intThat;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.excel.ExportExcel;




import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;




import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.system.util.UserUtils;
import com.alibaba.fastjson.JSONPath;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.seeyoui.kensite.bussiness.orderlang.productPrice.domain.ProductPrice;
import com.seeyoui.kensite.bussiness.orderlang.productPrice.service.ProductPriceService;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.domain.ProductSpec;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.service.ProductSpecService;
import com.seeyoui.kensite.bussiness.orderlang.userCart.domain.UserCart;
import com.seeyoui.kensite.bussiness.orderlang.userCart.domain.UserCartDTO;
import com.seeyoui.kensite.bussiness.orderlang.userCart.domain.UserCartModify;
import com.seeyoui.kensite.bussiness.orderlang.userCart.domain.UserCartVO;
import com.seeyoui.kensite.bussiness.orderlang.userCart.service.UserCartService;

/**
 * UserCart
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-02-07
 */

@Controller
@RequestMapping(value = "orderlang/userCart")
public class UserCartController extends BaseController {

	@Autowired
	private UserCartService userCartService;
	@Autowired
	private ProductSpecService productSpecService;
	@Autowired
	private ProductPriceService productPriceService;
	
	@RequestMapping("/goUserCart")
	public String goUserCart(){
		return "/bussiness/orderlang/customer/shopping_car";
	}

	/**
	 * 提交订单页面商品列表
	 * @param priceIds
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/findListByPriceIds", method=RequestMethod.POST)
	@ResponseBody
	public Result findListByPriceIds(String priceIds) throws Exception {
		List<String> priceIdList = Arrays.asList(priceIds.split(","));
		List<UserCartDTO> cartProductList = userCartService.findListByPriceIds(priceIdList);
		for (UserCartDTO userCartDTO : cartProductList) {
			String price = productPriceService.findDiscountPriceByUserLevel("shareholder", userCartDTO.getProductPriceId());
			userCartDTO.setDiscountPrice(price);
			userCartDTO.setSpecList(productSpecService.findListByProductPriceId(userCartDTO.getProductPriceId()));
		}
		if(cartProductList.size() > 0){
			return Result.success(cartProductList);
		}
		return Result.failure("查询失败");
	}
	
	@RequestMapping("/goBalance")
	public String goBalance(){
		return "/bussiness/orderlang/customer/balance";
	}


	/**
	 * 展示列表页面
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/orderlang/userCart/" + page, modelMap);
	}

	/**
	 * 根据ID查询单条数据
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
			@PathVariable String id) throws Exception {
		UserCart userCart = userCartService.findOne(id);
		return userCart;
	}

	/**
	 * 根据ID查询单条数据并返回相应表单
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		UserCart userCart = userCartService.findOne(id);
		modelMap.put("userCart", userCart);
		return new ModelAndView("bussiness/orderlang/userCart/" + page, modelMap);
	}

	/**
	 * 获取列表展示数据
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:select")
	@RequestMapping(value = "/list/data", method = RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, UserCart userCart) throws Exception {
		List<UserCart> userCartList = userCartService.findList(userCart);
		int total = userCartService.findTotal(userCart);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(userCartList);
		return eudg;
	}

	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:view")
	@RequestMapping(value = "/list/page", method = RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, UserCart userCart) throws Exception {
		List<UserCart> userCartList = userCartService.findList(userCart);
		int total = userCartService.findTotal(userCart);
		Page<UserCart> page = new Page<UserCart>(userCart.getPage(), userCart.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", userCartList);
		dataMap.put("page", page);
		return dataMap;
	}

	/**
	 * 获取所有数据
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:select")
	@RequestMapping(value = "/list/all", method = RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, UserCart userCart) throws Exception {
		List<UserCart> userCartList = userCartService.findAll(userCart);
		return userCartList;
	}

	/**
	 * 保存新增的数据
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:insert")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Result save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
			UserCart userCart) throws Exception {
		if (!beanValidator(modelMap, userCart)) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		userCart.setDelFlag("0");
		List<UserCart> lCarts = userCartService.findAll(null);
		/* 判断是否有相同产品--有则更新原有数据 无则插入新的数据 */
		if (lCarts != null && lCarts.size() > 0) {
			for (int i = 0; i < lCarts.size(); i++) {
					if (lCarts.get(i).getProductId().equals(userCart.getProductId())) {// 用相同productId做判断
						if (lCarts.get(i).getDelFlag().equals("0")) {// 判断flag值
							int quantity = Integer.parseInt(lCarts.get(i).getQuantity())
									+ Integer.parseInt(userCart.getQuantity());
							lCarts.get(i).setQuantity(String.valueOf(quantity));
							userCartService.update(lCarts.get(i));
							return Result.success(null, "添加成功");
						}
						else {
							userCart.setUserId(UserUtils.getUser(request).getId());
							userCartService.save(userCart);
							return Result.success(null, "添加成功");
						}
				}
			}
		}
		userCart.setUserId(UserUtils.getUser(request).getId());
		userCartService.save(userCart);
		return Result.success(null, "添加成功");
	}

	/**
	 * 保存修改的数据
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result update(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, UserCart userCart) throws Exception {
		if (!beanValidator(modelMap, userCart)) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		String json = request.getParameter("cartModifyJson");
		
		if (json!=null&&!json.equals("")) {
			List<UserCartModify> uModify=new Gson().fromJson(json,  new TypeToken<List<UserCartModify>>(){}.getType());
			for(UserCartModify uCartModify:uModify) {
				//遍历所有需要修改的商品列表
				UserCart uCart=userCartService.findOne(uCartModify.getId());
				uCart.setQuantity(uCartModify.getQuantity());
				userCartService.update(uCart);
			}
			return Result.success(null, "修改成功");
		}else {
			return Result.failure("修改失败");
		}
//		userCartService.update(userCart);
//		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
//		return null;
	}

	/**
	 * 删除数据库
	 * 
	 * @param modelMap
	 * @param userCartId
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:delete")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		userCartService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 假删除
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:delete")
	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	@ResponseBody
	public Result remove(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap,UserCart uCart,String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		
		for(int i=0;i<listId.size();i++){
			UserCart userCart=userCartService.findOne(listId.get(i));
			userCartService.remove(userCart);
			userCart.setDelFlag("1");
		}
		return Result.success(null, "删除成功");
//		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
	}

	/**
	 * 导出Excel数据
	 * 
	 * @param modelMap
	 * @param userCart
	 * @return
	 * @throws Exception
	 */
	// @RequiresPermissions("orderlang:userCart:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, UserCart userCart) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		List<UserCart> userCartList = userCartService.findAll(userCart);
		new ExportExcel(null, UserCart.class).setDataList(userCartList).write(response, fileName).dispose();
		return null;
	}

	/**
	 * 往购物车添加一条商品
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addCartForOne", method = RequestMethod.POST)
	@ResponseBody
	// 请求数据格式 {"cartJson":{"userId":"","productId":"","quantity":""}}
	public Result addCartForOne(HttpServletResponse response, HttpServletRequest request) {

		String json = request.getParameter("cartJson");
		if (json != null && !json.equals("")) {
			UserCart userCart = new Gson().fromJson(json, UserCart.class);
			if (userCart != null) {
				userCart.setDelFlag("0");
				userCartService.save(userCart);
				return Result.success(null, "添加成功");
			}
		} else {
			return Result.failure("添加失败");
		}
		return null;
	}

	/**
	 * 删除购物车内商品记录
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deletCart", method = RequestMethod.POST)
	@ResponseBody
	// 请求数据格式 {"id":""}
	public Result deletCart(HttpServletResponse response, HttpServletRequest request) {

		String id = request.getParameter("id");
		if (id != null && !id.equals("")) {
			List<String> ids = Arrays.asList(id.split(","));
			userCartService.delete(ids);
			return Result.success(null, "删除成功");
		} else {
			return Result.failure("删除失败");
		}
	}

	/**
	 * 修改购物车内一条商品记录
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	// 请求数据格式 {"cartJson":{"userId":"","id":"","quantity":""}}
	@RequestMapping(value = "/updateCartForOne", method = RequestMethod.POST)
	@ResponseBody
	public Result updateCartForOne(HttpServletResponse response, HttpServletRequest request) {

		String json = request.getParameter("cartJson");
		if (json != null && !json.equals("")) {
			String id = (String) JSONPath.read(json, "$.id");
			UserCart uCart = userCartService.findOne(id);
			uCart.setQuantity((String) JSONPath.read(json, "$.quantity"));
			userCartService.update(uCart);
			return Result.success(null, "修改成功");
		} else {
			return Result.failure("修改失败");
		}
	}

	/**
	 * 查询购物车内所有商品
	 * 
	 * @param response
	 * @param request
	 * @param userCart
	 * @return
	 */
	@RequestMapping(value = "/findAllCart", method = RequestMethod.POST)
	@ResponseBody
	public Result findAllCart(HttpServletResponse response, HttpServletRequest request, UserCart userCart) {
		userCart.setDelFlag("0");
		List<UserCart> lCarts = userCartService.findAll(userCart);
		if (lCarts != null && lCarts.size() > 0) {
			return Result.success(lCarts, "查询成功");
		} else {
			return Result.failure("查询失败");
		}

	}

	/**
	 * 查询当前用户购物车内所有商品
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryAllUserCart", method = RequestMethod.POST)
	@ResponseBody
	public Result queryAllUserCart(HttpServletResponse response, HttpServletRequest request, UserCartVO vUserCartVO) {
		vUserCartVO.setDelFlag("0");
		// 查出购物车内所有商品集合
		List<UserCartVO> lCartVOs = userCartService.queryAllUserCart(UserUtils.getUser(request).getId());// 用戶id
		// 每条商品 规格值重新赋值 放入 空集合内
		List<UserCartVO> responses = new ArrayList<UserCartVO>();
		if (lCartVOs != null && lCartVOs.size() > 0) {
			// 遍历原集合
			for (UserCartVO uVo : lCartVOs) {
				if (!uVo.getDelFlag().equals("1")) {
					List<ProductSpec> specs = productSpecService.findListByProductPriceId(uVo.getProdPriceId());
					uVo.setSpecs(specs);
					responses.add(uVo);// 赋值新集合
				}
			}
			return Result.success(responses, "查询成功");
		} else {
			return Result.failure("查询失败");
		}
	}

}
